import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/default/Kits.dart';
import 'package:juju/fake/fake_message_tool.dart';
import 'package:juju/model/ChatDataModel.dart';
import 'package:juju/model/UserInfoModel.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  ChatDataModel? data;
  TextEditingController? _msgTextEditingController;

  @override
  void initState() {
    super.initState();
    _msgTextEditingController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    data = ModalRoute.of(context)!.settings.arguments as ChatDataModel?;
    _enterConversation(data: data!);
    UserInfo target = data!.conversationInfo!.target;
    String title = target.username;
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: ListView.builder(
              itemBuilder: (BuildContext buildContext, int position) =>
                  _message(position),
              itemCount: data!.msgList.length,
            ),
          ),
          Container(
            color: Colors.grey[300],
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(6.0),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      child: TextField(
                        minLines: 1,
                        maxLines: 10,
                        controller: _msgTextEditingController,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.only(
                            left: 15.0,
                            right: 15.0,
                            top: 2.0,
                            bottom: 2.0,
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                        ),
                        style: const TextStyle(fontSize: 16.0),
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 8.0),
                  child: FloatingActionButton(
                    foregroundColor: Colors.green,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(50.0),
                    ),
                    onPressed: sendTextMessage,
                    child: const Text("发送"),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _message(int position) {
    TextMessage textMessage =
        TextMessage.fromJson(data!.msgList[position]!.toJson());
    bool isSend = data!.msgList[position].isSend;
    UserInfo? u = data!.conversationInfo!.target;
    return Row(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      textDirection: isSend ? TextDirection.rtl : TextDirection.ltr,
      // textDirection: position % 2 == 0 ? TextDirection.ltr : TextDirection.rtl,
      verticalDirection: VerticalDirection.up,
      children: <Widget>[
        Container(
          padding: const EdgeInsets.all(10.0),
          child: isSend
              ? chatAvatar(UserInfoModel.getInstance().myInfo!.avatarThumbPath)
              : chatAvatar(u!.avatarThumbPath),
        ),
        // Icon(isSend ? Icons.ac_unit : Icons.access_alarm),
        Text(
          textMessage.text,
          style: const TextStyle(fontSize: 16.0),
        ),
      ],
    );
  }

  void sendTextMessage() async {
    print(
        "========================= sendTextMessage ===========================\n");

    if (data!.conversationInfo == null) {
      return;
    }
    await data!.conversationInfo!
        .sendTextMessage(text: _msgTextEditingController!.text)
        .then(
      (value) {
        print(value.toJson());
        setState(() {
          data!.msgList.add(value);
          _msgTextEditingController!.text = "";
        });
      },
      onError: (error) {
        if (error is PlatformException) {
          PlatformException ex = error;
          print("======================= 发送消息异常 ========================");
          print("|\n|\n----- ${ex.code}");
          print("|\n|\n----- ${ex.details}");
          print("|\n|\n----- ${ex.message}");
        } else {
          print(error.toString());
        }
      },
    );
    // JMTextMessage msg = await data.jmConversationInfo
    //     .sendTextMessage(text: "send msg queen index $textIndex");
  }

  void _enterConversation({required ChatDataModel data}) async {
    await IMConf.getInstance()
        .getJmessage()
        .enterConversation(target: data.target);
  }
}
